<template>
  <!-- 添加或修改产品对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="图标" prop="photoUrl">
        <div class="photo">
          <el-upload
            name="file"
            :action="reqFileUrl"
            :accept="accept"
            :before-upload="beforeUpload"
            :headers="{'Authorization': 'Bearer ' + getToken()}"
            :show-file-list="false"
            :on-success="handleSuccess">
            <img v-if="form.photoUrl" :src="form.photoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="产品ID" prop="id">
        <el-input v-model="form.id" :disabled="idDisabled" placeholder="请输入产品ID" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="form.productName" placeholder="请输入产品名称" />
      </el-form-item>
      <el-form-item label="所属品类" prop="categoryId">
        <tree-select
          :show-count="true"
          v-model="form.categoryId"
          :options="categoryOptions"
          :normalizer="normalizer"
          placeholder="请选择所属品类"
        />
      </el-form-item>
      <el-form-item label="消息协议" prop="protocolId">
        <el-select v-model="form.protocolId" placeholder="请选择消息协议" class="select-width">
          <el-option
            v-for="dict in messageProtocol"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="传输协议" prop="transportProtocol">
        <el-select v-model="form.transportProtocol" placeholder="请选择传输协议" class="select-width">
          <el-option
            v-for="dict in transportProtocol"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="存储策略" prop="storePolicy">
        <el-select v-model="form.storePolicy" placeholder="请选择存储策略" class="select-width">
          <el-option
            v-for="dict in dict.type.iot_product_store_policy"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-radio-group v-model="form.deviceType">
          <el-radio
            v-for="dict in dict.type.iot_product_device_type"
            :key="dict.value" :label="dict.value"
          >{{dict.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="产品描述" prop="description">
        <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
import TreeSelect from "@riophae/vue-treeselect";
import { addProduct, getProduct, updateProduct } from '@/api/iot/product'
import { listCategory } from '@/api/iot/category'
import { getProtocols, getTransports } from '@/api/iot/protocol'

export default {
  name: 'ProductAddEdit',
  dicts: [ 'iot_product_device_type', 'iot_product_store_policy'],
  components: {
    TreeSelect,
  },
  data() {

    return {
      //上传图片路径
      // reqFileUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      reqFileUrl: 'https://www.sdzctech.cn',
      //限制图片格式
      accept: '.jpg,.jpeg,.png,.JPG,.JPEG,.svg,.SVG',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 品类树选项
      categoryOptions: [],
      // 表单参数
      form: {},
      // 产品id输入框显示状态
      idDisabled: false,
      // 物模型
      metadata: {
        // 属性
        properties: [],
        // 功能
        functions: [],
        // 事件
        events: [],
        // 标签
        tags: []
      },
      // 表单校验
      rules: {
        id: [
          { required: true, message: '产品ID不能为空', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '产品名称不能为空', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '所属品类不能为空', trigger: 'blur' }
        ],
        protocolId: [
          { required: true, message: '消息协议不能为空', trigger: 'change' }
        ],
        transportProtocol: [
          { required: true, message: '传输协议不能为空', trigger: 'change' }
        ],
        storePolicy: [
          { required: true, message: '存储策略不能为空', trigger: 'change' }
        ],
        deviceType: [
          { required: true, message: '设备类型不能为空', trigger: 'change' }
        ]
      },
      categoryMap: {},

      // 是否更新操作
      isUpdate: false,

      // 消息协议
      messageProtocol: [],
      // 传输协议
      transportProtocol: []
    }
  },
  watch: {
    open(state) {
      if (state) {
        this.getProtocols()
      }
    },
    'form.protocolId'(protocolId) {
      if (!protocolId) {
        this.transportProtocol = []
        return
      }
      if (protocolId) {
        this.getTransportProtocols(protocolId)
      }
    }
  },
  methods: {
    //获得令牌
    getToken() {
      return getToken()
    },
    //上传图片后成功的操作
    handleSuccess(response, file, fileList) {
      this.form.photoUrl = response.url
    },
    //上传之前的操作 验证
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2    //这里做文件大小限制
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 2M ',
          type: 'warning'
        })
      }
      return isLt2M
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productName: null,
        categoryId: null,
        protocolId: null,
        publishState: 0,
        transportProtocol: null,
        deviceType: null,
        description: null,
        createTime: null,
        updateTime: null,
        photoUrl: null
      }
      this.resetForm('form')
    },
    /** 查询品类下拉树结构 */
    getTreeselect() {
      listCategory().then(({ data }) => {
        if (!data) {
          return
        }
        this.categoryOptions = this.handleTree(data)

        data.forEach((item => this.categoryMap[item.id] = item))
      })
    },
    /** 转换品类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        label: node.categoryName
      }
    },
    /** 取消按钮操作 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.idDisabled = false
      this.reset()
      this.getTreeselect()
      this.open = true
      this.title = '添加产品'
      this.isUpdate = false
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.idDisabled = true
      this.reset()
      this.getTreeselect()
      getProduct(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改产品'
        this.isUpdate = true
      })
    },
    /** 提交按钮 */
    submitForm() {
      let that = this
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.isUpdate) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.$store.commit('PRODUCT_DATA', JSON.parse(JSON.stringify(this.form)))
            })
          } else {
            // 添加空的物模型
            this.form.metadata = JSON.stringify(this.metadata)
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.$store.commit('PRODUCT_DATA', JSON.parse(JSON.stringify(this.form)))
            })
          }
        }
      })
    },
    /** 获取协议支持 */
    getProtocols() {
      getProtocols().then(({ data }) => {
        this.messageProtocol = data || []
      })
    },
    /** 获取协议支持的传输协议 */
    getTransportProtocols(id) {
      getTransports(id).then(({ data }) => {
        this.transportProtocol = data || []
      })
    }
  }
}
</script>

<style lang="scss" scoped>

$width: 150px;
$height: 150px;

::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: $width;
  height: $height;
}

// 鼠标移入边框颜色
::v-deep .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: $width;
  height: $height;
  line-height: $height;
  text-align: center;
}

.avatar {
  width: $width;
  height: $height;
  display: block;
}

.photo {
  margin-left: 20%;
}
</style>
